package com.atguigu.gmall.user.service.impl;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.Jsons;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.user.vo.UserLoginSuccessVo;
import com.atguigu.gmall.user.vo.UserLoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.user.entity.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 用户登录
     * @param userLoginVo
     * @return
     */
    @Override
    public UserLoginSuccessVo login(UserLoginVo userLoginVo) {
        //查询数据库
        String encrypt = MD5.encrypt(userLoginVo.getPasswd());
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getLoginName, userLoginVo.getLoginName())
                .eq(UserInfo::getPasswd, encrypt));
        //判断数据库有无此数据
        if(userInfo == null){
            throw new GmallException(ResultCodeEnum.USER_PWD_INVAILD);
        }
        //登录成功
        UserLoginSuccessVo successVo = new UserLoginSuccessVo();
        String token = UUID.randomUUID().toString().replace("-", "");
        successVo.setToken(token);
        successVo.setNickName(userInfo.getNickName());
        //存redis
        stringRedisTemplate.opsForValue().set(RedisConst.USER_LOGIN + token, Jsons.tostr(userInfo),7, TimeUnit.DAYS);

        return successVo;
    }

    /**
     * 退出
     * @param token
     */
    @Override
    public void logout(String token) {
        //删除redis中缓存的数据
        stringRedisTemplate.delete(RedisConst.USER_LOGIN + token);
        //TODO 后序操作
    }
}




